package com.naizhuai.ui.management;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.entity.CommonLabel;
import com.naizhuai.ui.entity.management.PersonUserEditBean;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.RxUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;
import rx.functions.Action1;
import rx.subjects.PublishSubject;

/**
 * 个人操作界面
 */
public class CompanyUseOperatActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "CompanyUserDetailsMsgActivity";

    public static final String ENTER_TYPE_KEY = "enter_type_key";
    public static final String ENTER_FROM_ADD = "add_part";
    public static final int ENTER_FROM_EDIT = 2;

    public static final int RESULT_SAVE = 1000;
    public static final int RESULT_DELETE_FROM_COMPANY = 1001;
    public static final int RESULT_DELETE_FROM_DEPARTMENT = 1002;

    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.department_power_name)
    TextView departmentPowerName;
    @BindView(R.id.company_power_name)
    TextView companyPowerName;
    @BindView(R.id.department_power_setting)
    RelativeLayout departLayout;
    @BindView(R.id.company_power_setting)
    RelativeLayout comLayout;
    @BindView(R.id.department_img_arrow)
    ImageView departImageArrow;
    @BindView(R.id.company_img_arrow)
    ImageView comImageArrow;

    @BindView(R.id.delete_member)
    TextView deleteBtn;

    private PersonUserEditBean userEditBean;

    private ArrayList<CommonLabel> companyPowerLabels;
    private ArrayList<CommonLabel> departPowerLabels;
    private Subscription userinfoSub;
    private String enterType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBasicData();
    }


    private void initBasicData() {
        Bundle intentBundle = getIntent().getExtras();
        initLabelData();
        if (intentBundle != null) {
            userEditBean = (PersonUserEditBean) intentBundle.getSerializable(PersonUserBean.USER_KEY);
            enterType = getIntent().getStringExtra(ENTER_TYPE_KEY);
            if (!TextUtils.isEmpty(userEditBean.getPersonBean().getDepartmentId()))
                departLayout.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(enterType) && enterType.equals(ENTER_FROM_ADD))
                comLayout.setVisibility(View.GONE);
            requestUserPermission();
        }
    }

    private void initLabelData() {
        companyPowerLabels = new ArrayList<>();
        CommonLabel comLabel1 = new CommonLabel(ConstantsState.COM_MANAGER_POWER_LEVEL, ConstantsState.COM_MANAGER_POWER_LEVEL_STRING);
        CommonLabel comLabel2 = new CommonLabel(ConstantsState.COM_NORMAL_POWER_LEVEL, ConstantsState.COM_NORMAL_POWER_LEVEL_STRING);
        companyPowerLabels.add(comLabel1);
        companyPowerLabels.add(comLabel2);

        departPowerLabels = new ArrayList<>();
        CommonLabel departLabel1 = new CommonLabel(ConstantsState.DEPARTMENT_VICE_MANAGER_POWER, ConstantsState.DEPARTMENT_VICE_MANAGER_POWER_STRING);
        CommonLabel departLabel2 = new CommonLabel(ConstantsState.DEPARTMENT_NORMAL_POWER, ConstantsState.DEPARTMENT_NORMAL_POWER_STRING);
        departPowerLabels.add(departLabel1);
        departPowerLabels.add(departLabel2);

    }

    private void initView() {
        userName.setText(userEditBean.getPersonBean().getShowName());
        departmentPowerName.setText(userEditBean.getBeDepartPowerMsg());
        companyPowerName.setText(userEditBean.getBeCompanyPowerMsg());
    }

    private void requestUserPermission() {
        if (!RxUtils.isNetRunning(userinfoSub)) {
            userinfoSub = UserManageDataApiStoreIml.getInstance().getuserinfo().subscribe(new Observer<PersonUserBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    hideWaitDialog();
                    ApiException.showException(e, getActivityContext());
                }

                @Override
                public void onNext(PersonUserBean personUserBean) {
                    hideWaitDialog();
                    initView();
                    String userDepartmentId = personUserBean.getDepartmentId();
                    String userDepartmentCode = personUserBean.getDepartmentPowerCode();
                    String userCompanyCode = personUserBean.getCompanyPowerCode();
                    if (!TextUtils.isEmpty(enterType) && enterType.equals(ENTER_FROM_ADD)) {
                        deleteBtn.setVisibility(View.VISIBLE);
                        departLayout.setOnClickListener(CompanyUseOperatActivity.this);
                        departLayout.setVisibility(View.VISIBLE);
                        departImageArrow.setVisibility(View.VISIBLE);
                        return;
                    }
                    if (!userCompanyCode.equals(ConstantsState.COM_TARGET_MANAGER_LEVEL) || !isOperationSelf())
                        deleteBtn.setVisibility(View.VISIBLE);
                    if (userCompanyCode.equals(ConstantsState.COM_TARGET_MANAGER_LEVEL)) {
                        if (comLayout.getVisibility() == View.VISIBLE && !isOperationSelf()) {
                            comLayout.setOnClickListener(CompanyUseOperatActivity.this);
                            comImageArrow.setVisibility(View.VISIBLE);
                        }
                        departLayout.setOnClickListener(CompanyUseOperatActivity.this);
                        departImageArrow.setVisibility(View.VISIBLE);
                    } else {
                        if (userCompanyCode.equals(ConstantsState.COM_MANAGER_POWER_LEVEL) ||
                                (userDepartmentId.equals(userEditBean.getPersonBean().getDepartmentId()) &&
                                        userDepartmentCode.equals(ConstantsState.DEPARTMENT_MANAGER_POWER))) {
                            departLayout.setOnClickListener(CompanyUseOperatActivity.this);
                            departImageArrow.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });
            showWaitDiaLog(userinfoSub);
        }
    }

    private boolean isOperationSelf() {
        return getShareValue(PersonUserBean.USER_ID_KEY, "").equals(userEditBean.getPersonBean().getUid());
    }

    private PublishSubject<CommonLabel> initOptionsLabel(List<CommonLabel> result) {
        PublishSubject<CommonLabel> subject = PublishSubject.create();
        OptionsPickerView<CommonLabel> pvLabelOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonLabel key = result.get(options1);
                subject.onNext(key);
            }
        })
                .setTitleText(getString(R.string.power_setting_chosen))
                .setSubmitText(getString(R.string.next_step))
                .setCancelColor(ContextCompat.getColor(this, R.color.title_text_color))
                .setSubmitColor(ContextCompat.getColor(this, R.color.target_process_color))
                .setTextColorCenter(ContextCompat.getColor(this, R.color.title_text_color))
                .build();
        pvLabelOptions.setPicker(result);
        pvLabelOptions.show();
        return subject;
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_company_user_operate_layout;
    }

    @OnClick({R.id.base_back_icon, R.id.save_btn, R.id.delete_member})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_back_icon:
                super.onBackPressed();
                break;
            case R.id.department_power_setting:
                settingDepartmentPower();
                break;
            case R.id.company_power_setting:
                settingCompanyPower();
                break;
            case R.id.save_btn:
                setResult(RESULT_SAVE, subMitData());
                finish();
                break;
            case R.id.delete_member:
                PersonUserBean userBean = userEditBean.getPersonBean();
                if (!TextUtils.isEmpty(enterType) && enterType.equals(ENTER_FROM_ADD) || !TextUtils.isEmpty(userBean.getDepartmentId())) {
                    DialogUtils.showSureDialog(this, getString(R.string.delete_user_from_department), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            setResult(RESULT_DELETE_FROM_DEPARTMENT, subMitData());
                            finish();
                        }
                    });
                } else {
                    DialogUtils.showSureDialog(this, getString(R.string.delete_user_from_company), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            setResult(RESULT_DELETE_FROM_COMPANY, subMitData());
                            finish();
                        }
                    });
                }
                break;
        }
    }

    private Intent subMitData() {
        if (TextUtils.isEmpty(userEditBean.getAfCompanyPowerCode()))
            userEditBean.initCompanySave();
        if (TextUtils.isEmpty(userEditBean.getAfDepartPowerCode()))
            userEditBean.initDepartmentSave();
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PersonUserBean.USER_KEY, userEditBean);
        intent.putExtras(bundle);
        return intent;
    }

    private void settingCompanyPower() {
        initOptionsLabel(companyPowerLabels)
                .subscribe(new Action1<CommonLabel>() {
                    @Override
                    public void call(CommonLabel labels) {
                        userEditBean.setAfCompanyPowerCode(labels.key);
                        userEditBean.setAfCompanyPowerMsg(labels.label);
                        companyPowerName.setText(labels.label);
                    }
                });
    }

    private void settingDepartmentPower() {
        initOptionsLabel(departPowerLabels)
                .subscribe(new Action1<CommonLabel>() {
                    @Override
                    public void call(CommonLabel labels) {
                        userEditBean.setAfDepartPowerCode(labels.key);
                        userEditBean.setAfDepartPowerMsg(labels.label);
                        departmentPowerName.setText(labels.label);
                    }
                });
    }

}
